package org.finesys.common.log.trace.interceptor.redis;

import static org.finesys.common.log.constants.TraceConstants.REDIS_EXECUTE_AFTER;
import static org.finesys.common.log.constants.TraceConstants.REDIS_EXECUTE_BEFORE;

import java.lang.reflect.Method;

import javax.annotation.Nonnull;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.finesys.common.log.trace.interceptor.AbstractInterceptor;
import org.jetbrains.annotations.Nullable;
import org.springframework.cglib.proxy.MethodProxy;

/**
 * redis增加
 */
public class SpringRedisCommandInterceptor extends AbstractInterceptor implements MethodInterceptor, org.springframework.cglib.proxy.MethodInterceptor {
    private static final String IS_PIPELINED = "isPipelined";

    private static final String CLOSE = "close";

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        String beforeTag = REDIS_EXECUTE_BEFORE;
        String afterTag = REDIS_EXECUTE_AFTER;
        if (IS_PIPELINED.equals(method.getName()) || CLOSE.equals(method.getName())) {
            beforeTag += "_" + method.getName();
            afterTag += "_" + method.getName();
        }
        executeBefore(beforeTag);
        Object result = method.invoke(o, objects);
        executeAfter(afterTag);
        return result;
    }

    @Nullable
    @Override
    public Object invoke(@Nonnull MethodInvocation invocation) throws Throwable {
        return intercept(invocation.getThis(), invocation.getMethod(), invocation.getArguments(), null);
    }
}
